const paginationDecorator = (Sup = class Empty {}) => class PaginationController extends Sup {
  constructor(queryService = null, queryFnName = 'query') {
    super();

    this.paginationService = queryService;
    this.queryFnName = queryFnName;
    this.$table = {
      fetchTimes: 0,
      isTableLoading: false,
      pagination: {
        ITEMS_PER_PAGE: 10,
        MAX_SIZE: 5,
        currentPage: 1,
        total: 0,
      },
    };

    this.mapParams = {};
  }

  $toggleOrder(columnName) {
    if (!this.mapParams.sortType) {
      this.mapParams.columnName = columnName;
      this.mapParams.sortType = 2;
    } else {
      this.mapParams.sortType = (this.mapParams.sortType === 2) ? 1 : 2;
    }
    this.$paginationQuery();
  }

  $setQueryCallback(cbFn) {
    this.callbackFn = cbFn;
  }

  $paginationQuery(param = this.mapParams) {
    this.$table.isTableLoading = true;
    return this
      .paginationService[this.queryFnName]({
        mapParams: param,
        page: this.$table.pagination.currentPage,
        size: this.$table.pagination.ITEMS_PER_PAGE,
      })
      .then((res) => {
        this.$table.pagination.total = res.total;
        return res;
      })
      .then(this.callbackFn)
      .finally(() => {
        this.$table.fetchTimes += 1;
        this.$table.isTableLoading = false;
      });
  }

};

export default paginationDecorator;
